package com.op.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.op.constants.CommonStatusConstant;
import com.op.entity.QuestionBank;
import com.op.entity.QuestionBankAudit;
import com.op.mapper.QuestionBankAuditMapper;
import com.op.model.vo.QuestionBankReviewVo;
import com.op.service.QuestionBankAuditService;
import com.op.service.QuestionBankService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (QuestionBankAudit)表服务实现类
 *
 * @author 孤焰
 * @since 2021-12-11 19:28:04
 */
@Service("questionBankAuditService")
public class QuestionBankAuditServiceImpl extends MPJBaseServiceImpl<QuestionBankAuditMapper, QuestionBankAudit> implements QuestionBankAuditService {
    @Resource
    QuestionBankAuditMapper questionBankAuditMapper;
    @Resource
    QuestionBankService questionBankService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchThrough(List<Long> idList) {
        // 批量更新题库的公共题库属性
        List<QuestionBank> questionBanks = idList.stream().map(id -> {
            QuestionBank questionBank = new QuestionBank();
            questionBank.setId(id);
            questionBank.setIsCommon(CommonStatusConstant.BOTH_STATUS);
            return questionBank;
        }).collect(Collectors.toList());
        questionBankService.updateBatchById(questionBanks);
        // 批量删除待审批请求
        if (!this.delBatchByQuestionBankId(idList)) {
            throw new RuntimeException("没有发现部分的删除请求");
        }
        return true;
    }

    @Override
    public Page<QuestionBankReviewVo> joinPage(Page<QuestionBankAudit> page, QuestionBankAudit questionBankAudit) {
        MPJLambdaWrapper<QuestionBankAudit> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.innerJoin(QuestionBank.class, QuestionBank::getId, QuestionBankAudit::getQuestionBankId)
                .selectAll(QuestionBank.class);

        return (Page<QuestionBankReviewVo>) questionBankAuditMapper.selectJoinPage(page, QuestionBankReviewVo.class, mpjLambdaWrapper);
    }

    @Override
    public boolean delBatchByQuestionBankId(List<Long> bankIdList) {
        LambdaQueryWrapper<QuestionBankAudit> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.in(QuestionBankAudit::getQuestionBankId, bankIdList);
        if (questionBankAuditMapper.delete(lambdaQueryWrapper) == bankIdList.size()) {
            return true;
        }
        return false;
    }

    @Override
    public int count() {
        return questionBankAuditMapper.selectCount(null);
    }
}

